package com.wash.shoes.controller.mobile;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.R;
import com.wash.shoes.common.enums.OrderStatusEnum;
import com.wash.shoes.domain.dto.MobileOrderDto;
import com.wash.shoes.domain.dto.MobileOrderListDto;
import com.wash.shoes.domain.order.SaveOrderComponent;
import com.wash.shoes.domain.vo.OrderDetailVo;
import com.wash.shoes.entity.*;
import com.wash.shoes.service.*;
import com.wash.shoes.util.CodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author ljg
 * @since 2024-08-29
 */
@Log4j2
@Api(tags = {"移动端-洗护订单"})
@RestController
@RequestMapping("/mobile-api/order")
public class OrderMController {

    @Resource
    OrderService orderService;

    @Resource
    SaveOrderComponent saveOrderComponent;

    @Resource
    OrderGoodService orderGoodService;

    @Resource
    ShoeService shoeService;

    @Resource
    private OrderCommentService orderCommentService;

    @Resource
    OrderTransportService orderTransportService;


    public void init() {
        List<OrderPo> orderPos = orderService.getOrderByComeFrom("3");
        for (OrderPo orderPo : orderPos) {
            if (orderPo.getStatus().equals(OrderStatusEnum.CANCEL.getStatus())) {
                log.info("===");
                deleteOrder(orderPo.getId());
            }
        }
    }

    @ApiOperation("用户的订单列表")
    @PostMapping("/userOrderList")
    public R<Page<OrderDetailVo>> userOrderList(@RequestBody MobileOrderListDto orderPo) {
        log.info("用户的订单列表查询 {}", JSONObject.toJSONString(orderPo));
        if (StrUtil.isBlank(orderPo.getComeFrom())) {
//            orderPo.setComeFrom("4");
        }
        Page<OrderDetailVo> page = orderService.userOrderList(orderPo);
        return R.ok(page);
    }


    @ApiOperation("删除订单")
    @PostMapping("/deleteOrder")
    @Transactional
    public R<String> deleteOrder(String orderId) {
        log.info("删除订单 deleteOrder orderId {}", orderId);
        OrderPo orderPo = orderService.getById(orderId);
        if (orderPo == null) {
            orderPo = orderService.getByOrderNo(orderId);
        }
        orderId = orderPo.getId();
        orderService.removeById(orderPo);
        List<OrderGoodPo> orderGoodPoList = orderGoodService.getOrderGoods(orderId);
        if (!orderGoodPoList.isEmpty()) {
            orderGoodService.removeBatchByIds(orderGoodPoList);
        }

        OrderCommentPo orderCommentPo = orderCommentService.getByOrderId(orderId);
        if (orderCommentPo != null) {
            orderCommentService.removeById(orderCommentPo.getId());
        }

        List<OrderTransportPo> orderTransportPo = orderTransportService.getByOrderId(orderId);
        if (orderTransportPo != null) {
            for (OrderTransportPo po : orderTransportPo) {
                orderTransportService.removeById(po.getId());
            }
        }
        return R.ok("String");
    }

    @ApiOperation("保存订单")
    @PostMapping("/saveMobileOrder")
    @Transactional
    public R<OrderPo> saveMobileOrder(@RequestBody MobileOrderDto mobileOrder) {
        log.info("保存订单参数 {}", JSONObject.toJSONString(mobileOrder));
        CodeUtil.clearCurrentCacheCode();
        return R.ok(saveOrderComponent.process(mobileOrder, null, "X", null, null));
    }

    @Autowired
    private IAccessoriesService accessoriesService;

    @ApiOperation("获取订单的详情")
    @GetMapping("/getOrderDetail")
    public R<OrderDetailVo> getOrderDetail(String orderId) {
        log.info("获取订单的详情 orderId {}", orderId);
        OrderPo orderPo = orderService.getById(orderId);
        if (orderPo == null) {
            orderPo = orderService.getByOrderNo(orderId);
        }
        if (orderPo == null) {
            orderPo = orderService.getByMtOrderId(orderId);
        }
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        BeanUtils.copyProperties(orderPo, orderDetailVo);
        List<OrderGoodPo> orderGoodPoList = orderGoodService.getOrderGoods(orderId);
        orderDetailVo.setOrderGoodPoList(orderGoodPoList);
        List<ShoePo> shoePoList = shoeService.getByOrderId(orderId);
        if (CollectionUtil.isNotEmpty(shoePoList)) {
            //填充物品的配饰信息
            shoePoList.forEach(e -> {
                if (Objects.isNull(e.getQualityInspectorStatus())) {
                    e.setQualityInspectorStatus("0");
                }
                //根据订单id和物品id查询对应的配饰数据
                List<AccessoriesPo> accessoriesPoList = accessoriesService.list(new LambdaQueryWrapper<AccessoriesPo>().eq(AccessoriesPo::getOrderId, e.getOrderId()).eq(AccessoriesPo::getBizId, e.getId()));
                if (CollectionUtil.isNotEmpty(accessoriesPoList)) {
                    //转换填充配饰信息
                    e.setAccessorVoList(accessoriesPoList.stream().map(accessoriesPo -> {
                        ShoePo.AccessorVo accessorVo = new ShoePo.AccessorVo();
                        accessorVo.setType(accessoriesPo.getType());
                        accessorVo.setWashCode(accessoriesPo.getWashCode());
                        accessorVo.setStatus(accessoriesPo.getStatus());
                        accessorVo.setId(accessoriesPo.getId());
                        return accessorVo;
                    }).collect(Collectors.toList()));
                }
            });
        }


        orderDetailVo.setShoePoList(shoePoList);
        List<String> nameList = orderGoodPoList.stream().map(OrderGoodPo::getName).collect(Collectors.toList());
        orderDetailVo.setOrderGoodsNames(String.join(",", nameList));
        // 物流信息
        List<OrderTransportPo> orderTransportPoList = orderTransportService.getByOrderId(orderId);
        orderDetailVo.setOrderTransportPoList(orderTransportPoList);

        return R.ok(orderDetailVo);
    }

    @ApiOperation("用户取消订单")
    @PostMapping("/cancelOrder")
    @Transactional
    public R<OrderPo> cancelOrder(String orderId, String remark) {
        log.info("取消订单 取消订单的参数为 {} {}", orderId, remark);
        if (StrUtil.isBlank(remark)) {
            //默认的原因
            remark = "买多了/买错了/不需要了";
        }
        return R.ok(orderService.cancel(orderId, remark));
    }

    @ApiOperation("用户订单的数量")
    @PostMapping("/userOrderNum")
    public R<Map<String, Integer>> userOrderNum(@RequestBody MobileOrderListDto mobileOrderListDto) {

        log.info("用户订单的数量查询 {}", JSONObject.toJSONString(mobileOrderListDto));
        Map<String, Integer> data = orderService.userOrderNum(mobileOrderListDto);
        return R.ok(data);
    }

}

